<?php

/**
 * 对象模块仓库
 * @author	Lucky
 */
class ObjectStorage
{
	/**
	 * 对象集
	 * @var	array
	 */
	protected static $objects = array();
	
	/**
	 * 任务对象集
	 * @var	array
	 */
	protected static $taskObjects = array();
	
	/**
	 * 注册需要保存的对象
	 * @param	aBaseModel $obj	
	 * @return	object
	 */
	public static function register( aBaseModel & $obj )
	{
		if( !isset( self::$objects[$obj->getUserId()][$obj->getCacheKey()] ) )
		{
			self::$objects[$obj->getUserId()][$obj->getCacheKey()] = $obj;
		}
	}
	
	/**
	 * 注册需要保存的对象
	 * @param	Task_Abstract $obj	
	 * @return	object
	 */
	public static function registerTask( Task_Abstract & $obj )
	{
		if( !isset( self::$taskObjects[$obj->getUserId()][$obj->getCacheKey()] ) )
		{
			self::$taskObjects[$obj->getUserId()][$obj->getCacheKey()] = $obj;
			self::register( $obj );
		}
	}
	
	/**
	 * 保存所有对象
	 * @return	boolean
	 */
	public static function save()
	{
		while( self::$taskObjects )
		{
			foreach( self::$taskObjects as $userId => $objects )
			{
				foreach( $objects as $objKey => $obj )
				{
					$obj->sendActions();
					if( $obj->isActionListEmpty() )
					{
						unset( self::$taskObjects[$userId][$objKey] );
					}
				}
				if( empty( self::$taskObjects[$userId] ) )
				{
					unset( self::$taskObjects[$userId] );
				}
			}
		}
		
		foreach( self::$objects as $userId => $objects )
		{
			foreach( $objects as $obj )
			{
				$obj->save();
			}
		}
		
		self::$objects = array();
	}
}

?>